package com.mvp.shq.washer.ui.userCenter;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.zxing.activity.CaptureActivity;
import com.jaeger.library.StatusBarUtil;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.base.BaseActivity;
import com.mvp.shq.washer.entity.User;
import com.mvp.shq.washer.rxbus.RxBus;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.utils.DateUtils;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.JumpUtil;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.StringUtils;
import com.mvp.shq.washer.utils.T;
import com.mvp.shq.washer.view.widget.EditDialog;
import com.orhanobut.logger.Logger;
import com.zhy.autolayout.AutoRelativeLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@RuntimePermissions
public class UserCenterActivity extends BaseActivity<UserCenterPresenter, UserCenterModel> implements UserCenterConstract.View {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.img_user)
    ImageView imgUser;
    @BindView(R.id.tv_gender)
    TextView tvGender;
    @BindView(R.id.arl_gender)
    AutoRelativeLayout arlGender;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.arl_mobile)
    AutoRelativeLayout arlMobile;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.arl_birthday)
    AutoRelativeLayout arlBirthday;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.arl_age)
    AutoRelativeLayout arlAge;
    @BindView(R.id.tv_occupation)
    TextView tvOccupation;
    @BindView(R.id.arl_occupation)
    AutoRelativeLayout arlOccupation;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.arl_address)
    AutoRelativeLayout arlAddress;
    private User user;
    private TimePickerView pvTime;
    private OptionsPickerView pvGender;
    private List<String> genders;
    private Date dateBirthday;
    private String gender;
    private EditDialog dialog;
    private String nickName;

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_center;
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.white), 0);
        setUserInfo();
    }

    @Subscribe(code = EventCode.UPDATE_USER)
    public void setUserInfo(){
        user = SpUtil.getUser();
        if (user != null){
            tvUsername.setText(user.getNickname());
            tvBalance.setText("账户余额:"+user.getRechargeBalance().add(user.getGivenMoney())+"元");
            tvMobile.setText(user.getMobile());
            tvGender.setText(user.getGender());
            long time = DateUtils.StrToDate(user.getBirthday()).getTime()/1000;
            tvBirthday.setText(DateUtils.formatDate(time));
            imageUtil.loadCircleImage(user.getFaceurl(),imgUser,R.mipmap.my_headshot,R.mipmap.my_headshot);
        }
    }

    @OnClick({R.id.back,R.id.all_nickname,R.id.img_user, R.id.arl_gender, R.id.arl_mobile, R.id.arl_birthday, R.id.arl_age, R.id.arl_occupation, R.id.arl_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.all_nickname:
                if (dialog == null){
                    EditDialog.Builder builder = new EditDialog.Builder(context);
                    dialog = builder.setMessage("请输入新昵称")
                            .setEditListener(new EditDialog.editListener() {
                                @Override
                                public void save(String content) {
                                    showLoadingDialog(true);
                                    nickName = content;
                                    presenter.updateNickname(content);
                                    dialog.dismiss();
                                }

                                @Override
                                public void cancel() {
                                    dialog.dismiss();
                                }
                            }).createTwoButtonDialog();
                }
                dialog.show();
                break;
            case R.id.back:
                finish();
                break;
            case R.id.img_user:
                UserCenterActivityPermissionsDispatcher.toChooseImgWithCheck(this);
                break;
            case R.id.arl_gender:
                if (pvGender == null){
                    pvGender = new OptionsPickerView.Builder(this,new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            gender = genders.get(options1);
                            showLoadingDialog(true);
                            presenter.updateGender(gender);
                        }
                    }).setCancelColor(ContextCompat.getColor(context,R.color.text_color_1))
                            .setSubmitColor(ContextCompat.getColor(context,R.color.money)).build();
                    genders = new ArrayList<>();
                    genders.add("男");
                    genders.add("女");
                    pvGender.setPicker(genders);
                }
                pvGender.show();
                break;
            case R.id.arl_mobile:
                JumpUtil.toModifyMobile(context);
                break;
            case R.id.arl_birthday:
                if (pvTime == null){
                    pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            dateBirthday = date;
                            showLoadingDialog(true);
                            presenter.updateBirthday(dateBirthday);
                        }
                    }).setCancelColor(ContextCompat.getColor(context,R.color.text_color_1))
                            .setSubmitColor(ContextCompat.getColor(context,R.color.money))
                            .setType(new boolean[]{true,true,true,false,false,false}).setLabel("","","","","","").build();
                    pvTime.setDate(Calendar.getInstance());
                }
                pvTime.show();
                break;
            case R.id.arl_age:
                break;
            case R.id.arl_occupation:
                break;
            case R.id.arl_address:
                break;
        }
    }

    @NeedsPermission({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    public void toChooseImg() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(false)
                .start(this, PhotoPicker.REQUEST_CODE);
    }
    @OnShowRationale({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(context)
                .setMessage("是否开启相机权限")
                .setPositiveButton("同意", (dialog, button) -> request.proceed())
                .setNegativeButton("拒绝", (dialog, button) -> request.cancel())
                .show();
        Toast.makeText(context, "showRationaleForCamera", Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        Toast.makeText(context, "拒绝相机权限将无法修改头像", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        Toast.makeText(context, "相关权限无法使用", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UserCenterActivityPermissionsDispatcher.onRequestPermissionsResult(this,requestCode,grantResults);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logger.d("resultCode:"+resultCode+"------------requestCode:"+requestCode);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) { //RESULT_OK = -1
            if (data != null){
                List<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (photos == null || photos.size() <= 0){
                    return;
                }
                File file = new File(photos.get(0));
                showLoadingDialog(true);
                compressImg(file);
            }
        }
    }

    private void compressImg(File file){
        Luban.with(this)
                .load(file)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
                        presenter.updateFace(requestBody);
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoadingDialog();
                    }
                }).launch();
    }


    @Override
    public void uBirthDayS() {
        tvBirthday.setText(DateUtils.getTime(dateBirthday));
        long time = dateBirthday.getTime()/1000;
        user.setBirthday(DateUtils.formatDate(time));
        SpUtil.setUser(user);
        RxBus.get().send(EventCode.UPDATE_USER);
    }

    @Override
    public void uBirthdayF(String msg) {
        T.show(msg);
    }

    @Override
    public void uGenderS() {
        tvGender.setText(gender);
        user.setGender(gender);
        SpUtil.setUser(user);
        RxBus.get().send(EventCode.UPDATE_USER);
    }

    @Override
    public void uGenderF(String msg) {
        T.show(msg);
    }

    @Override
    public void uNicknameS() {
        tvUsername.setText(nickName);
        user.setNickname(nickName);
        SpUtil.setUser(user);
        RxBus.get().send(EventCode.UPDATE_USER);
    }

    @Override
    public void uNickNameF(String msg) {
        T.show(msg);
    }

    @Override
    public void uFaceS(String faceUrl) {
        user.setFaceurl(faceUrl);
        SpUtil.setUser(user);
        imageUtil.loadCircleImage(user.getFaceurl(),imgUser);
        RxBus.get().send(EventCode.GET_USER_INFO);
    }

    @Override
    public void uFaceF(String msg) {
        T.show(msg);
    }
}
